package com.vhall.component.service.redpacket.tasks;

import com.alibaba.fastjson.JSON;
import com.vhall.component.entity.rebroadcast.RedPacketRecordEntity;
import com.vhall.component.service.redpacket.common.RedpacketConstants;
import com.vhall.component.service.redpacket.service.CacheService;
import com.vhall.component.service.redpacket.service.RedPacketRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RecordTask {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private RedPacketRecordService redPacketRecordService;

    /**
     * stream 处理记录消息, 如果失败, 数据会进入comp:redpacket:queue:record
     * 队列, 这个定时任务的作用仅仅用于修复数据
     */
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void receiverMessage() {
        String data = cacheService.popFromQueue(RedpacketConstants.QUEUE_RED_PACKET_RECORD, false, null);
        log.info("stream处理记录消息,消息记录是：{}", data);
        saveAction(data);
    }

    /**
     * 红包领取记录入库消费队列
     */
    public void saveAction(String data) {
        if (StringUtils.isEmpty(data)) {
            return;
        }
        RedPacketRecordEntity records = JSON.parseObject(data, RedPacketRecordEntity.class);
        if (StringUtils.isNotEmpty(data)) {
            redPacketRecordService.add(records);
            // 对income和order表的写入。
        }
        data = cacheService.popFromQueue(RedpacketConstants.QUEUE_RED_PACKET_RECORD, false, null);
        while (StringUtils.isNotEmpty(data)) {
            saveAction(data);
        }
    }
}